<template>
  <view class="page">
    <!-- 导航栏 -->
    <tui-navigation-bar title="扫码点单"></tui-navigation-bar>

    <header class="header">
      <view @click="finalGetConsumeDetail(loginInfo)">消费详情</view>
      <view class="room font-weight-bold">{{ loginInfo.roomid }}</view>
      <tui-icon name="search" size="22" color="#edd2b2" @tap="openSearchModal"></tui-icon>
    </header>

    <view
      class="scroll-container"
      :style="{
        height: scrollContainerHeight
      }"
    >
      <my-container :data="categoryList" refresh @refresh="handleInit">
        <!-- 左侧小类 -->
        <scroll-view scroll-y scroll-with-animation class="left-tab">
          <view
            v-for="(category, index) in categoryList"
            :key="category.id"
            class="left-tab-item"
            :class="[currentTabIndex === index ? 'active' : '']"
            @tap.stop="selectTab(category, index)"
          >
            <view class="left-tab-item-text">
              {{ category.name }}
            </view>

            <!-- <view v-if="category.selectNumber" class="select-number" style="top: 14px">
            {{ category.selectNumber }}
          </view> -->
          </view>
        </scroll-view>

        <!-- 右侧商品 -->
        <block v-for="(category, index) in categoryList" :key="index">
          <scroll-view v-if="index === currentTabIndex" scroll-y scroll-with-animation class="goods-container">
            <!-- <view class="goods-tab-item-name">{{ category.name }}</view> -->

            <block v-for="rowData in goodsList" :key="rowData.id">
              <view v-if="category.id === rowData.STypeId" class="goods-item-box">
                <!-- 商品图片 -->
                <view class="goods-item-img">
                  <image v-if="rowData.img" class="width-100 height-100" :src="rowData.img" mode="aspectFill"></image>
                </view>

                <!-- 商品内容 -->
                <view class="goods-item-content">
                  <!-- 标题 -->
                  <!-- {{ rowData.Lscs }} -->
                  <view class="goods-item-title text-ellipsis">{{ rowData.name }}</view>

                  <view v-if="rowData.Lscs" class="is-flex fs-xxs mt-2">
                    <!-- <tui-tag type="gold" margin="0 4px 0 0" padding="4px 5px" size="18rpx" plain> 满 {{ getLscs(rowData.Lscs, '满') }} 件起 </tui-tag> -->

                    <tui-tag type="gold" margin="0 4px 0 0" padding="4px 5px" size="16rpx" plain>
                      满 {{ getLscs(rowData.Lscs, '满') }} 起 买 {{ getLscs(rowData.Lscs, '买') }} 送 {{ getLscs(rowData.Lscs, '送') }}
                    </tui-tag>
                  </view>

                  <!-- mt-2 -->
                  <view class="goods-item-bottom">
                    <!-- 商品价格 -->
                    <view class="goods-item-price text-price mr-5 white-space-nowrap">
                      <text class="pr-4">{{ rowData.Price }}</text>
                      <text class="fs-xs">{{ rowData.Unit }}</text>
                    </view>

                    <!-- 点击添加 选规格 / - num + -->
                    <view class="choose-box pb-2 white-space-nowrap">
                      <!-- 多选 -->
                      <view v-if="isMeal(rowData.set)" class="multi-select" @click="showForm(rowData, rowData.id)">
                        <text>选规格</text>

                        <view v-if="rowData.selectNumber" class="select-number">{{ rowData.selectNumber }}</view>
                      </view>

                      <!-- 单选 -->
                      <block v-else>
                        <NumberBox :value="rowData.selectNumber" :min="getLscs(rowData.Lscs, '满', 1)" :rowData="rowData" @change="addGoodsChange"></NumberBox>
                      </block>
                    </view>
                  </view>
                </view>
              </view>
            </block>

            <!-- 占位高度 -->
            <view style="height: 10px"></view>
          </scroll-view>
        </block>

        <!-- 购物车 -->
        <view class="foot" :style="{ height: footHeight }">
          <view class="mask" @click="hideShoppingCar"></view>

          <!-- 位于底部的购物车显示栏 -->
          <view class="foot-box">
            <view class="foot-box-content" @click="showShoppingCar">
              <view class="cart-icon-box">
                <view class="tag cartNum" v-if="currentRoomShopCart.totalNumber > 0">{{ currentRoomShopCart.totalNumber }}</view>
                <image :src="currentRoomShopCart.totalNumber ? '/static/images/shop/cart.png' : '/static/images/shop/cart2.png'" mode=""></image>
              </view>
              <view v-if="currentRoomShopCart.totalPrice > 0" class="price-box">
                <view class="total-text">合计 ： </view>
                <view class="text-price font-weight-bold">{{ currentRoomShopCart.totalPrice }} </view>
              </view>
            </view>
            <view class="foot-box-btn">
              <view class="submit" v-if="currentRoomShopCart.totalPrice > 0" @click="submit">下单</view>
            </view>
          </view>

          <!-- 点击详情展开的购物车框 -->
          <view class="cart-box" :style="{ display: showCar ? 'flex' : 'none' }" style="transition: 1s all">
            <view class="cart-box-header">
              <view class="cart-box-header-left" @click="clearShopCart">
                <my-icon name="trash" size="14" color="#edd2b2"></my-icon>
                <text class="ml-5">清空购物车</text>
              </view>
              <view class="cart-box-header-title">购物车</view>
              <tui-icon name="close" size="22" color="white" class="header-close-icon" @click="hideShoppingCar"></tui-icon>
            </view>

            <scroll-view scroll-y :scroll-top="carGoodsScrollTop" class="cart-goods-scroll">
              <view v-if="currentShopCart && currentShopCart.length > 0" class="cart-goods-container">
                <view class="cart-goods-item-box" v-for="rowData in currentShopCart" :key="rowData.id" style="flex-flow: column nowrap">
                  <block v-if="rowData.selectNumber > 0">
                    <!-- 商品内容 -->
                    <view class="box-content">
                      <view>{{ rowData.name }}</view>
                      <!-- 购物车 - 选数量 -->
                      <view v-if="!isMeal(rowData.set)" class="choose-box">
                        <NumberBox :value="rowData.selectNumber" :min="getLscs(rowData.Lscs, '满', 1)" :rowData="rowData" @change="addGoodsChange"></NumberBox>
                      </view>

                      <view v-else class="multi-select" @click="addGoodsChange(0, rowData)">
                        <text>删除</text>
                        <view v-if="rowData.selectNumber" class="select-number">{{ rowData.selectNumber }}</view>
                      </view>
                    </view>

                    <!-- 套餐配送详情 -->
                    <view v-if="(isMeal(rowData.set) && rowData.mealForm && rowData.mealForm.length > 0) || rowData.lsNumber" class="cart-meal-form">
                      <!-- 例送数据 -->
                      <view v-if="rowData.lsNumber" class="cart-meal-form-item">
                        <view class="is-flex items-center">
                          <text class="mr-5">{{ rowData.name }} </text>
                          <tui-tag padding="4px 5px" width="100%" size="20rpx" type="gold" plain>例送</tui-tag>
                        </view>
                        <view class="right-number">x {{ rowData.lsNumber }}</view>
                      </view>

                      <block v-for="meal in rowData.mealForm" :key="meal.setinfoid">
                        <view class="cart-meal-form-item">
                          <view>{{ meal.goodsname }}</view>

                          <!-- {{ meal.goodsunit }} -->
                          <view class="right-number">x {{ meal.selectNumber }}</view>
                        </view>
                      </block>
                    </view>
                  </block>
                </view>

                <!-- 占位高度 -->
                <view style="height: 10px;"></view>
              </view>

              <view v-else class="cart-no-data">
                <tui-no-data :fixed="false" imgUrl="/static/images/no-data/no-data.png">暂无更多数据</tui-no-data>
              </view>
            </scroll-view>
          </view>
        </view>
      </my-container>
    </view>

    <!-- 套餐 -->
    <ModalMealForm
      ref="mealFormModal"
      :selectMeal="currentMeal"
      :selectMealForm="selectMealFormStatistics.originMealForm"
      :selectMealFormGoods="selectMealFormStatistics.goods"
      :selectMealFormGroups="selectMealFormStatistics.groups"
      @mealFormModalClose="mealFormModalClose"
    ></ModalMealForm>

    <!-- 搜索 -->
    <ModalSearch ref="searchModal"></ModalSearch>

    <!-- 消费详情 -->
    <modal-consume-detail ref="consumeDetailModal"></modal-consume-detail>

    <!-- loading -->
    <my-loading ref="loading"></my-loading>
  </view>
</template>

<script>
import NumberBox from '@/pages/shop/components/number-box/number-box.vue'
import ModalMealForm from '@/pages/shop/components/modal-meal-form/modal-meal-form.vue'
import ModalSearch from '@/pages/shop/components/modal-search/modal-search.vue'

import common from '@/pages/shop/mixins/common'
import addGood from '@/pages/shop/mixins/add-good'
export default {
  name: 'Shop',
  mixins: [common, addGood],
  components: {
    NumberBox,
    ModalMealForm,
    ModalSearch
  },
  data() {
    return {
      // 显示购物车 - modal
      showCar: false,
      // 购物车中商品滚动条位置
      carGoodsScrollTop: 0,
      // foot 高度
      footHeight: '0',

      // 预设当前项的值
      currentTabIndex: 0,

      // 当前房台购物车对象
      currentRoomShopCart: null,
      // 当前门店购物车数据数组
      currentShopCart: null,

      // 是否初始化第一个 tab 选项的商品
      ifInitFirstTabGoods: true,
      // 商品分类信息列表
      categoryList: [],
      // 菜品列表
      goodsList: [],
      // 已经请求过的菜品小类 id 集合
      isAddCategoryType: [],

      /* css 一些变量值 */
      headerHeight: '50px'

      /* css 一些变量值 */
    }
  },
  computed: {
    // 中间滚动区域高度
    scrollContainerHeight() {
      const footHeight = '60px'
      return `calc(100vh - ${this.navBarHeight} - ${this.headerHeight} - ${footHeight})`
    }
  },
  onLoad(options) {
    // 支付成功返回该页，清空购物车
    const encodeOptions = this.$encode(options)
    const clearShopCart = this.$format(encodeOptions, 'clearShopCart')

    if (clearShopCart) {
      this.clearShopCart()
    }
  },
  onShow() {
    this.handleInit()
  },
  methods: {
    handleInit() {
      try {
        this.initLoginInfo().then(async res => {
          const categoryList = await this.getGoodsType()

          // 是否初始化第一个 tab 栏目数据
          if (this.ifInitFirstTabGoods) {
            const categoryFirst = this.$format(categoryList, '0')
            if (!categoryFirst) return
            this.$refs.loading.open()
            await this.shopGetGoods(categoryList[0].id)

            this.init()
            return
          }
        })
      } catch (err) {
        console.err(err)
      }
    },

    /**
     * 获取菜品小类列表
     * 场景：未知
     */
    getGoodsType() {
      return new Promise((resolve, reject) => {
        const baseParam = this.getBase(['token', 'selectuniacid', 'bid', 'roomid'])
        if (!baseParam) return reject()
        console.param('获取菜品小类列表', baseParam)
        this.$api
          .getGoodsType(baseParam)
          .then(res => {
            console.res('获取菜品小类列表', res)
            this.categoryList = this.$format(res, 'data', [])
            resolve(this.categoryList)
          })
          .catch(err => {
            console.err('获取菜品小类列表', err)
            this.errMsg(err, '获取菜品小类列表失败')
            reject(err)
          })
          .finally(() => {
            this.$refs.loading.close()
          })
      })
    },

    /**
     * 获取菜品列表
     * 必填: 'token', 'selectuniacid':登录的商家id, 'bid': 门店id, 'roomid': 房台id , 'stypeid': 小类id
     * 场景：未知
     */
    shopGetGoods(stypeid) {
      if (!stypeid) return this.$msg('text', '菜品小类id为空')

      // --- 判断是否已经请求过 start ---
      const isAddCategoryType = this.isAddCategoryType
      if (isAddCategoryType.includes(stypeid)) return
      isAddCategoryType.push(stypeid)
      // --- 判断是否已经请求过 end ---

      const baseParam = this.getBase(['token', 'selectuniacid', 'bid', 'roomid', 'ordernum'])
      if (!baseParam) return
      Object.assign(baseParam, { stypeid })
      console.param('获取菜品列表', baseParam)
      this.$api
        .getGoods(baseParam)
        .then(res => {
          console.res('获取菜品列表', res)

          const goodsList = this.goodsList
          const goods = this.$format(res, 'data')
          goodsList.push(...goods)

          this.init()
        })
        .catch(err => {
          console.err('获取菜品列表', err)
          this.errMsg(err, '获取菜品列表失败')
        })
        .finally(() => {})
    },

    // 去结算
    submit() {
      this.$open('/shop/order-preview', 'nt')
    },

    // 左侧侧边栏分类点击
    selectTab(item, index) {
      this.currentTabIndex = index

      if (!item.id) return this.$msg('text', '该菜品小类不存在')
      this.shopGetGoods(item.id)
    },

    openSearchModal() {
      this.$refs.searchModal.open()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/pages/shop/styles/shop.scss';
@import '~@/pages/shop/styles/cart.scss';
</style>
